package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;

import dbutil.DBUtil;
//import net.sf.json.JSONArray;

/**
 * Servlet implementation class UpdateMessagesServlet
 */
@WebServlet("/UpdateMessagesServlet")
public class UpdateMessagesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateMessagesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		JSONArray jsonarray = new JSONArray();
		response.setContentType("text/html;charset=utf-8");
  		request.setCharacterEncoding("UTF-8");
  		String Mid = request.getParameter("Mid");
//  		String Mid = "7";
        String title = request.getParameter("title");
		String content = request.getParameter("content");
		String author = request.getParameter("author");
		String type = request.getParameter("type");
//		HttpSession httpSession=request.getSession();
  		DBUtil db=new DBUtil();
		Connection conn = db.getConn();
		try {
			String sql;
			sql="select * from newsdetail where Mid!='"+Mid+"' and title='"+title+"'";
			ResultSet rs = db.getResult(sql);
			if(rs.next()) {
				System.out.println("标题重复");
				response.getWriter().println("<script>alert(\"修改失败,标题重复\");window.location.href=\"./PAGES/UpdateNews.jsp\"</script>");
			}else {
				sql = "UPDATE newsdetail SET title=?,content=?,author=?,time=now(),type=? WHERE Mid='"+Mid+"'";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setString(1, title);
				ps.setString(2, content);
				ps.setString(3, author);
				ps.setInt(4, Integer.parseInt(type));
				int result = ps.executeUpdate();
				if (result != 0) {
					System.out.println("修改成功");
					response.getWriter().println("<script>alert(\"编辑成功\");window.location.href=\"./ADMIN/Admin.jsp\"</script>");
				}else {
					System.out.println("编辑失败");
					response.getWriter().println("<script>alert(\"编辑失败\");window.location.href=\"./PAGES/UpdateNews.jsp\"</script>");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(db!=null)
				db.release();//关闭数据库
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
